package pack.afa;

import java.net.URL;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

public class WidgetProvider extends AppWidgetProvider {
    private static final String FEED_URL="https://twitter.com/statuses/user_timeline/247483633.rss";
    private static final String NODE_ITEM_ID="item";
    private static final String CHECK_STRING="free today from @amazonappstore for Android ";
    private static final String REMOVE_STRING="amazonappstore: Get ";
    public static final String INTENT_EXTRA_NAME="appName";
    public static final String INTENT_EXTRA_URL="appUrl";
    private static final int MAX_NUM_CHECKED=4;
    static Format formatter=new SimpleDateFormat("MMM dd");

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
	RemoteViews views=new RemoteViews(context.getPackageName(), R.layout.widget_layout);
	views.setTextViewText(R.id.widget1AppTitle, context.getString(R.string.widget_no_data));
	// Build the widget update
	ArrayList<String> list=parseFeed();
	if (list != null) {
	    // Handle download click
	    Intent serviceIntent=new Intent(context, AmazonFreeAppOfTheDayWidgetActivity.class);
	    serviceIntent.removeExtra(INTENT_EXTRA_NAME);
	    serviceIntent.putExtra(INTENT_EXTRA_NAME, list.get(0));
	    serviceIntent.putExtra(INTENT_EXTRA_URL, list.get(1));
	    serviceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	    PendingIntent pendingIntent=PendingIntent.getActivity(context, 0, serviceIntent,
		PendingIntent.FLAG_UPDATE_CURRENT);
	    views.setOnClickPendingIntent(R.id.widget1AppTitle, pendingIntent);
	    views.setTextViewText(R.id.widget1AppTitle, list.get(0));
	}
	else {
	    views.setTextViewText(R.id.widget1AppTitle, context.getString(R.string.widget_data_error));
	}
	views.setTextViewText(R.id.widget1Date, formatter.format(new Date()));
	// Push update for this widget to the home screen
	ComponentName thisWidget=new ComponentName(context, WidgetProvider.class);
	AppWidgetManager manager=AppWidgetManager.getInstance(context);
	manager.updateAppWidget(thisWidget, views);
    }

    private static ArrayList<String> parseFeed() {
	ArrayList<String> list=new ArrayList<String>();
	String titleApp, urlApp;
	try {
	    URL url=new URL(FEED_URL);
	    DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
	    DocumentBuilder db=dbf.newDocumentBuilder();
	    Document doc=db.parse(new InputSource(url.openStream()));
	    doc.getDocumentElement().normalize();
	    NodeList itemList=doc.getElementsByTagName(NODE_ITEM_ID);
	    for (int i=0; i < MAX_NUM_CHECKED; ++i) {
		// MAX_NUM_CHECKED used for optimization: we care only about recent items.
		Node item=itemList.item(i);
		Node n=item.getChildNodes().item(1);
		if (n.getNodeType() == Node.ELEMENT_NODE) {
		    String title=n.getFirstChild().getNodeValue();
		    if (title.contains(CHECK_STRING)) {
			titleApp=title.substring(REMOVE_STRING.length(), title.indexOf(CHECK_STRING) - 1);
			urlApp=title.substring(title.indexOf(CHECK_STRING) + CHECK_STRING.length(), title.length());
			list.add(titleApp);
			list.add(urlApp);
		    }
		}
	    }
	    return list;
	}
	catch (Exception e) {
	    return list;
	}
    }

}